#!/usr/bin/env bash

# Set script_dir
script_dir="$(dirname "$(realpath "$0")")"
docker_tag="mbrav/dotfiles:latest"
uid=$(id -u)
gid=$(id -g)
user="$USER"
mount_from=$(pwd)
mount_to="/home/${user}/mount"

# Source util functions
source "${script_dir}/_util"

ran_col_str "Utility for running mbrav dotfiles inside an ephemeral docker container"

command -v docker >/dev/null || error_msg "Please install docker" 1

# Function to display help message
display_help() {
	echo "Usage: $0 [options]"
	echo
	echo "Options:"
	echo "  -h    Show this help message"
	echo "  -u    Pass user's home directory inside the container"
	echo
	exit 0
}

# Parse the options using getopts
while getopts "hu" opt; do
	case ${opt} in
	h)
		display_help
		;;
	u)
		info_msg "Setting mount from to ${HOME}"
		mount_from="$HOME"
		mount_to="/home/${user}"
		;;
	\?)
		error_msg "Invalid option: -$OPTARG"
		exit 1
		;;
	esac
done

# Detect if running on macOS
if [[ "$(uname)" == "Darwin" ]]; then
	info_msg "Running on macOS, adjusting GID to 1000 avoid conflicts"
	gid="1000"
fi

info_msg "Using user: ${user}"
info_msg "UID/GID:    ${uid}/${gid}"
info_msg "Mount from: ${mount_from}"
info_msg "Mount to:   ${mount_to}"

if docker image inspect "${docker_tag}" >/dev/null; then
	info_msg "Docker container present, skipping build"
else
	info_msg "No docker container, building..."
	docker build \
		--progress=plain \
		-f "${script_dir}/../../../Dockerfile" \
		--build-arg DOCKER_USER="${user}" \
		--build-arg DOCKER_UID="${uid}" \
		--build-arg DOCKER_GID="${gid}" \
		--tag "${docker_tag}" \
		"${script_dir}/../../../." &&
		success_msg "Container ${docker_tag} built"
fi

[[ $? -ne 0 ]] && error_msg "Failed to build image" 1

# Print mount if source exists
function mount_if() {
	# $1 - Source mount
	# $2 - Destination mount
	if [ -f "$1" ] || [ -d "$1" ]; then
		echo "--mount type=bind,source="${1}",target="${2}",readonly"
	fi
}

info_msg "Running ${docker_tag} interactively with ${mount_from} as mount to ${mount_to} and user '${uid}:${gid}'"

docker run -it --rm \
	--name "tmp-${mount_from##*/}" \
	--user "${uid}:${gid}" \
	--volume "${mount_from}:${mount_to}:rw" \
	$(mount_if "/var/log" "/var/log") \
	"${docker_tag}" &&
	success_msg "Exited dotfiles container"
